//
//  LYCNetworkTool.m
//  爱鲜蜂
//
//  Created by 廖易诚 on 16/6/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "LYCNetworkTool.h"
#import "AFNetworking.h"

@interface LYCNetworkTool ()

@property (assign, nonatomic) AFHTTPSessionManager *manager;

@end

@implementation LYCNetworkTool


- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer = [[AFJSONRequestSerializer alloc]init];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    }
    return _manager;
}

+ (instancetype)shareTool {
    static LYCNetworkTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[LYCNetworkTool alloc] init];
    });
    return instance;
}

- (void)requestMethod:(Method)method urlString:(NSString *)urlString params:(NSDictionary *)params progress:(progress)progress success:(success)success failure:(failure)failure {
    
    if (method == GET) {
        // get请求
        [self.manager GET:urlString parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            if (progress) {
                progress(downloadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(task,error);
            }
        }];
    } else {
        // post请求
        [self.manager POST:urlString parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            if (progress) {
                progress(downloadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(task,error);
            }
        }];
    }
}


@end
